from datetime import datetime
from flask import request
from app import db
from app.models import Dataset, Apply, User
from app.utils import response, response_get
from flask import Blueprint

dataset_bp = Blueprint('dataset1', __name__)


@dataset_bp.route('/upload_dataset', methods=['POST'])
def upload_dataset():
    user_id = request.args.get('user_id')
    dataset_name = request.args.get('dataset_name')
    size = request.args.get('size')
    dataset_address = request.args.get('dataset_address')
    dataset_describe = request.args.get('dataset_describe')
    print(user_id, dataset_name, size, dataset_address, dataset_describe)
    # 根据 user_name 查找 user_id
    user = User.query.filter_by(user_id=user_id).first()
    if not user:
        return response(400)

    # 创建新的数据集实例
    new_dataset = Dataset(
        user_id=user.user_id,
        dataset_name=dataset_name,
        size=size,
        dataset_address=dataset_address,
        dataset_describe=dataset_describe,
    )
    db.session.add(new_dataset)
    db.session.commit()

    return response(200)


@dataset_bp.route('/self_dataset', methods=['GET'])
def get_datasets_by_user():
    user_id = request.args.get('user_id', type=int)
    limit = request.args.get('limit', 10, type=int)
    page = request.args.get('page', 1, type=int)
    sort_by = request.args.get('sort_by', 'dataset_id')  # 默认按照 dataset_id 排序
    sorting_order = request.args.get('sorting_order', 'desc')  # 默认升序
    status = request.args.get('status', None)  # 默认没有状态过滤
    search = request.args.get('search', None)  # 默认没有搜索过滤
    print(user_id,limit,page,sort_by,sorting_order,status,search)
    # 验证用户信息
    user = User.query.get(user_id)
    if not user:
        return response(400)

    # 构建查询
    query = Dataset.query.filter_by(user_id=user_id)
    if status:
        query = query.filter_by(dataset_state=status)
    if search:
        query = query.filter(Dataset.dataset_name.like(f'%{search}%'))

    # 排序
    if sorting_order == 'desc':
        query = query.order_by(db.desc(getattr(Dataset, sort_by)))
    else:
        query = query.order_by(getattr(Dataset, sort_by))

    # 执行分页查询
    pagination = query.paginate(page=page, per_page=limit, error_out=False)
    datasets = pagination.items
    total = pagination.total

    # 构建响应数据
    datasets_data = []
    for dataset in datasets:
        datasets_data.append({
            'dataset_id': dataset.dataset_id,
            'dataset_name': dataset.dataset_name,
            'size': dataset.size,
            'dataset_describe': dataset.dataset_describe,
            'dataset_address': dataset.dataset_address,
            'dataset_use': dataset.dataset_use,
            'dataset_time': dataset.dataset_time.strftime('%Y-%m-%d %H:%M:%S') if dataset.dataset_time else '',
            'dataset_state': dataset.dataset_state,
        })

    response_data = {
        'code': 200,
        'data': datasets_data,
        'pagination': {
                'page': page,
                'perpage': limit,
                'total': total
            }
    }

    return response_get(200, response_data)


@dataset_bp.route('/other_dataset', methods=['GET'])
def get_datasets_not_by_user():
    user_id = request.args.get('user_id', type=int)
    limit = request.args.get('limit', 10, type=int)
    page = request.args.get('page', 1, type=int)
    sort_by = request.args.get('sort_by', 'dataset_id')  # 默认按照 dataset_id 排序
    sorting_order = request.args.get('sorting_order', 'desc')  # 默认升序
    status = request.args.get('status', None)  # 状态过滤
    search = request.args.get('search', None)  # 搜索过滤

    # 验证用户信息
    user_search = User.query.get(user_id)
    if not user_search:
        return response(400)

    # 构建查询并排除指定user_id的数据
    query = Dataset.query.filter(Dataset.user_id != user_id)
    if status:
        query = query.filter_by(dataset_state=status)
    if search:
        query = query.filter(Dataset.dataset_name.like(f'%{search}%'))

    # 排序
    if sorting_order == 'desc':
        query = query.order_by(db.desc(getattr(Dataset, sort_by)))
    else:
        query = query.order_by(getattr(Dataset, sort_by))

    # 执行分页查询
    pagination = query.paginate(page=page, per_page=limit, error_out=False)
    datasets = pagination.items
    total = pagination.total

    datasets_data = []
    for dataset in datasets:
        user = User.query.get(dataset.user_id)
        print(dataset.user_id,user)
        # 使用 one_or_none() 来避免尝试访问 None 对象的属性
        apply = db.session.query(Apply).filter(
            Apply.applicant_id == user_id,
            Apply.dataset_id == dataset.dataset_id
        ).order_by(Apply.apply_id.desc()).first()
        if dataset.dataset_state == 'private':
            continue
        # 创建 datasets_data 列表的字典项，为 apply 对象可能为 None 的情况提供默认值
        if apply is not None:
            if apply.apply_state == 'waiting':
                state = 'waiting'
            elif apply.apply_state == 'approve':
                state = 'available'
            elif apply.apply_state == 'reject':
                state = 'disavailable'
            datasets_data.append({
                'dataset_id': dataset.dataset_id,
                'dataset_name': dataset.dataset_name,
                'size': dataset.size,
                'dataset_describe': dataset.dataset_describe,
                "dataset_use": dataset.dataset_use,
                "dataset_time": dataset.dataset_time,
                "user_id": user.user_id,
                "user_name": user.user_name,
                "avatar_url": user.avatar_url,
                "available": state,
                "apply_describe": apply.apply_describe if apply else '',
                "expiration_time": apply.expiration_time if apply else '',
            })
        else:
            datasets_data.append({
                'dataset_id': dataset.dataset_id,
                'dataset_name': dataset.dataset_name,
                'size': dataset.size,
                'dataset_describe': dataset.dataset_describe,
                "dataset_use": dataset.dataset_use,
                "dataset_time": dataset.dataset_time,
                "user_id": user.user_id,
                "user_name": user.user_name,
                "avatar_url": user.avatar_url,
                "available": 'disavailable',
                "apply_describe": apply.apply_describe if apply else '',
                "expiration_time": apply.expiration_time if apply else '',
            })

    # 现在 datasets_data 列表包含了每个 dataset 的信息，以及与 Apply 对象相关的信息或者默认值

    response_data = {
        'code': 200,
        'data': datasets_data,
        'pagination': {
                'page': page,
                'perpage': limit,
                'total': total
            }
    }

    return response_get(200, response_data)


@dataset_bp.route('/change_dataset', methods=['POST'])
def delete_dataset():
    dataset_id = request.args.get('dataset_id')
    dataset_state = request.args.get('dataset_state')

    # 验证请求数据
    if not dataset_id or not dataset_state:
        return response(400)

    # 查找匹配的数据集
    dataset = Dataset.query.filter_by(dataset_id=dataset_id).first()
    if not dataset:
        return response(400)

    dataset.dataset_state = dataset_state
    db.session.commit()

    return response(200)


@dataset_bp.route('/apply', methods=['POST'])
def get_user_check_applications():
    applicant_id = request.args.get('applicant_id')
    dataset_id = request.args.get('dataset_id')
    apply_describe = request.args.get('apply_describe')
    expiration_time = request.args.get('expiration_time')
    print(applicant_id, dataset_id, apply_describe, expiration_time)
    dataset = Dataset.query.filter_by(dataset_id=dataset_id).first()
    if not dataset:
        return response(400)
    dt = datetime.strptime(expiration_time, "%Y-%m-%dT%H:%M:%S.%fZ")
    application_data = {
        'applicant_id': applicant_id,
        'checker_id': dataset.user_id,
        'dataset_id': dataset_id,
        'apply_describe': apply_describe,
        'expiration_time': expiration_time,
    }

    # 创建一个新的 Apply 对象
    new_application = Apply(
        applicant_id=applicant_id,
        checker_id=dataset.user_id,  # 假设 checker_id 是 dataset 的一个字段
        dataset_id=dataset_id,
        apply_describe=apply_describe,
        expiration_time=dt,
        apply_state='waiting'
    )

    # 将新的 Apply 对象添加到数据库会话中
    db.session.add(new_application)

    db.session.commit()
    # 返回分页后的申请信息和分页详情
    return response(200, application_data)


@dataset_bp.route('/application_approve', methods=['POST'])
def application_approve():
    # 首先，找到对应的申请记录
    apply_id = request.args.get('apply_id')
    application = Apply.query.filter_by(apply_id=apply_id).first()

    if not application:
        # 如果没有找到申请记录
        return response(400)

    # 修改申请的状态
    application.apply_state = 'approve'
    db.session.commit()

    return response(200)


@dataset_bp.route('/application_reject', methods=['POST'])
def application_reject():
    apply_id = request.args.get('apply_id')
    application = Apply.query.filter_by(apply_id=apply_id).first()

    if not application:
        return response(400)

    # 修改申请的状态
    application.apply_state = 'reject'
    db.session.commit()

    return response(200)


@dataset_bp.route('/get_applications', methods=['GET'])
def application_check():
    user_id = request.args.get('user_id', type=int)
    limit = request.args.get('limit', 10, type=int)
    page = request.args.get('page', 1, type=int)
    sort_by = request.args.get('sort_by', 'apply_id')  # 默认按照 apply_id 排序
    sorting_order = request.args.get('sorting_order', 'desc')  # 默认升序
    status = request.args.get('status', None)  # 状态过滤
    print(user_id)
    # 构建查询
    query = Apply.query.filter_by(checker_id=user_id)
    if status:
        query = query.filter_by(apply_state=status)

    # 排序
    if sorting_order == 'desc':
        query = query.order_by(db.desc(getattr(Apply, sort_by)))
    else:
        query = query.order_by(getattr(Apply, sort_by))

    # 执行分页查询
    pagination = query.paginate(page=page, per_page=limit, error_out=False)
    applications = pagination.items
    total = pagination.total

    # 构建响应数据
    applications_data = []
    for application in applications:
        # 获取申请者的名称和头像
        applicant = User.query.get(application.applicant_id)
        dataset = Dataset.query.get(application.dataset_id)
        applications_data.append({
            'apply_id': application.apply_id,
            'dataset_name': dataset.dataset_name if dataset else '',
            'dataset_describe': dataset.dataset_describe if dataset else '',
            'apply_describe': application.apply_describe,
            'expiration_time': application.expiration_time.strftime('%Y-%m-%d %H:%M:%S') if application.expiration_time else '',
            'applicant_name': applicant.user_name if applicant else '',
            'applicant_id': application.applicant_id,
            'avatar_url': applicant.avatar_url if applicant else '',
            'apply_state': application.apply_state,
        })

    response_data = {
        'code': 200,
        'data': applications_data,
        'pagination': {
                'page': page,
                'perpage': limit,
                'total': total
            }
    }

    return response_get(200, response_data)
